
local p = `1'
global data "/cluster/projects/p1061/inga/AIS"
capture log close
log using "$data/logs/log`p'_hrs", replace
sysdir set PLUS $data/ado

use $data/input514NP/trips_hrs`p', clear

forvalues l=1(1)15 {

local k= `l'-1

rename D_* D`k'_*
rename A_a D_acid
rename A_t D_Ttime

sort  D_a D_Tt 


levelsof D_a, local(Da)

foreach i in `Da' {
di "`k'_`i'"
joinby D_a D_T using $data/input514NP/trips_Thrs`i', update unmatched(master)
drop _merge
*keep only fastest for given start time

quietly g tt=A_t - D0_t 
quietly egen mintt=min(tt) if A_a!=., by(D0_t A_a)
quietly  drop if tt!=mintt & A_a!=.
drop mintt

*keep only fastest for given arrival time
quietly egen mintt=min(tt) if A_a!=., by(A_t A_a)
quietly  drop if tt!=mintt & A_a!=.
drop tt mintt 

}


*replace missings with last port data
replace A_acid = D_ac if A_acid==.
replace A_t = D_Tt if A_t==.

*drop intermediate times
drop D_T

*drop return trips
forvalues j=0(1)`k' {
drop if A_acid==D`j'_acid & A_acid!=D_acid
}

replace D_a = A_a if D_a==D`k'_a


local m=`k'-1
local n=`k'-2

if `m'>=1 {
replace D`k'_a = D_a if D`k'_a==D`m'_a
}


while `m'>=1 {
local o = `m'+1
replace D`m'_a=D`o'_a if D`m'_a==D`n'_a
local m = `m'-1
local n = `n'-1
}

duplicates drop

*redo this for the ones that had no match in the last round
quietly g tt=A_t - D0_t 
quietly egen mintt=min(tt) if A_a!=., by(D0_t A_a)
quietly  drop if tt!=mintt & A_a!=.
drop mintt

*keep only fastest for given arrival time
quietly egen mintt=min(tt) if A_a!=., by(A_t A_a)
quietly  drop if tt!=mintt & A_a!=.
drop tt mintt

* drop routes with more stops
egen nhops = rownvals(*acid)
egen minhops=min(nhops), by(D0_ac D0_t A_aci A_t)
keep if nhops==minhop
drop minhops nhops
display "$S_TIME"
}

save $data/server_outputNP/hrs`p'_12, replace
capture log close


